package ua.com.globallogic.basecamp.krasnyanskiy.dds.queue;

import java.util.NoSuchElementException;

public class SimpleArrayQueue<E> {
    private Object[] data;
    private int initialCapacity;
    private int size = 0;

    public SimpleArrayQueue() {
        this(4);
    }

    public SimpleArrayQueue(int initialCapacity) {
        if (initialCapacity < 0) {
            throw new IllegalArgumentException("Illegal Capacity: " +
                    initialCapacity);
        }
        this.initialCapacity = initialCapacity;
        data = new Object[initialCapacity];
    }

    public boolean offer(E elem) {
        if (size < initialCapacity) {
            data[size++] = elem;
        } else {
            initialCapacity *= 2;
            Object[] newArray;
            newArray = new Object[initialCapacity];

            System.arraycopy(data, 0, newArray, 0, data.length);
            data = newArray;
            data[size++] = elem;
        }
        return true;
    }

    public E remove() {
        E elem = poll();
        if (elem == null) {
            throw new NoSuchElementException();
        } else {
            return elem;
        }
    }

    public E poll() {
        if (size > 0) {
            E elem = (E) data[0];
            System.arraycopy(data, 1, data, 0, size - 1);
            data[size - 1] = null;
            size--;
            return elem;
        } else {
            return null;
        }
    }

    public E element() {
        E elem = peek();
        if (elem != null) {
            return elem;
        } else {
            throw new NoSuchElementException();
        }

    }

    public E peek() {
        if (size > 0) {
            return (E) data[0];
        } else {
            return null;
        }
    }
}
